<template>
  <div>
      <el-cascader v-if="dataType==='static'" v-bind="$attrs" v-model="staticSelected" :options="optionsCopy" ref="cascader" style="width: 100%"
          @change="input" :props="props" @visible-change="expandChange" :show-all-levels="showAllLevels">
      </el-cascader>
      <el-cascader
            :show-all-levels="showAllLevels"
            v-else v-bind="$attrs"
            expandTrigger="click"
            v-model="selected"
            style="width: 100%"
            :options="option"
            ref="cascader"
            @change="input"
            @visible-change="visibleChange"
            :props="customerProps">
      </el-cascader>
  </div>
</template>
<script>
import {
  getColumnData,
  getDictData,
  sourceTestList
} from '@/api/custom/formDesigner'
import {
  getAllListData
} from "@/api/custom/formPoster";
export default {
  data() {
    return {
      modalKey: 0,
      customerProps: {},
      testOption: [],
      option: [], //动态数据选项
      updateView: true,
      selected: [], //选中值
      optionsCopy: [],
      showTree: true,
      staticSelected: [], // 静态数据选中值
      tableData: [] //表单数据
    }
  },
  props: ['dataType', //数据类型
    'options', //静态选项
    'value', //组件值
    'fields', //级联数据源配置
    'props', //级联组件参数配置
    'showAllLevels' // 是否展示全路径
  ],
  mounted() {
      // 制造option，以便初始化回显值
      if (this.dataType === 'dynamic') {
          if (Array.isArray(this.value)) {
              this.selected = [...this.value]
              let copyOption = []
              this.value.forEach((item, index) => {
                  if (index === 0) {
                      copyOption.push({
                          label: item,
                          value: item
                      })
                  }
                  if (index === 1) {
                    copyOption[0].children = [];
                      copyOption[0].children.push({
                          label: item,
                          value: item
                      })
                  }
                  if (index === 2) {
                    copyOption[0].children[0].children = [];
                      copyOption[0].children[0].children.push({
                          label: item,
                          value: item
                      })
                  }
                  if (index === 3) {
                    copyOption[0].children[0].children[0].children = [];
                      copyOption[0].children[0].children[0].children.push({
                          label: item,
                          value: item
                      })
                  }
              })
              this.option = [...copyOption]
          }
      } else {
          this.staticSelected = [...this.value]
      }
  },
  watch: {
    value(val) {
      if (this.dataType === 'dynamic') {
          this.selected = [...this.value]
      } else {
          this.staticSelected = [...this.value]
      }
    },
    fields: {
        handler (newVal) {
            setTimeout(() => {
                this.makeProps()
            }, 0);
        }
    }
  },
  created () {
      if (this.dataType === 'dynamic') {
          setTimeout(()=>{
                this.makeProps()
            },500)
      } else {
        if (this.value?.length > 0) {
            let keys = [...this.value]
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(this.options, keys, index, str)
            this.makeOptions(str)
        } else {
            this.optionsCopy = [...this.options]
        }
      }
  },
  methods: {
    makeProps () {
        const _this = this
        _this.customerProps = {
            ..._this.props,
            lazy: true,
            lazyLoad (node, resolve) {
                if (node?.data?.value) {
                    if (node.level === _this.fields.length) {
                        resolve([])
                    } else {
                        sourceTestList( _this.fields[node.level].tableName).then(rsp => {
                            if (rsp.code === 0) {
                                let nodes = rsp.data?.rowMaps.map((item)=>{
                                    return {
                                        label:item[_this.fields[node.level].datas[0].showName],
                                        value:item[_this.fields[node.level].datas[0].fieldName],
                                        parent: item[_this.fields[node.level].datas[0]?.parent]
                                    }
                                })
                                if (node.data.value) {
                                    nodes = nodes.filter(curVal => {
                                        return curVal.parent === node.data.value
                                    }) || []
                                }
                                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                                resolve(nodes);
                            }
                        })
                    }
                }
            }
        }
    },
    expandChange (list) {
        this.optionsCopy = [...this.options]
    },
    getLabelByKey(options, key, index, str) {
        options?.length > 0 && options.forEach((item) => {
          if (item.value.toString() === key[index] + '' || item.label === key[index] + '') {
            str.push({label: item.label, value: key[index]})
            index++
            index < key.length && this.getLabelByKey(item.children, key, index, str)
            return true
          }
        })
    },
    makeOptions (list) {
        let copyOption = []
        list.forEach((item, index) => {
            if (index === 0) {
                copyOption.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 1) {
            copyOption[0].children = [];
                copyOption[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 2) {
            copyOption[0].children[0].children = [];
                copyOption[0].children[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
            if (index === 3) {
            copyOption[0].children[0].children[0].children = [];
                copyOption[0].children[0].children[0].children.push({
                    label: item.label,
                    value: item.value
                })
            }
        })
        this.optionsCopy = [...copyOption]
    },
    input(val,index) {
      this.$emit('input', val)
      this.$emit('change', val)
    },
    visibleChange (flag) {
      if (flag && this.dataType === 'dynamic') {
          this.$emit('input', [])
          this.$emit('change', [])
          this.getTableData(this.selected[0] || '')
      } else {
          // this.option = []
      }
    },
    //获取表单所有数据
    async getTableData(val) {
      // 新需求适配多个表单
      const _this = this
      await sourceTestList(_this.fields[0].tableName).then(rsp => {
            if (rsp.code === 0) {
                _this.option = rsp.data?.rowMaps.map((item)=>{
                    return {
                        label:item[_this.fields[0].datas[0].showName],
                        value:item[_this.fields[0].datas[0].fieldName]
                    }
                })
            }
      })
    },
    /**
     * 已弃用
     */
    //获取动态选项
    async getDynamicOptions() {
      let options = []
      for (let i = 0; i < this.fields[0].datas.length; i++) {
        let opt = this.fields[0].datas[i]
        //获取对应列数据
        let values = await getColumnData({
          tableName: this.formName,
          column: opt.fieldName,
        })
        values.data.map((item) => {
          let node = { //构造节点
            label: item,
            value: item
          }
          let child = this.getChildren(opt.fieldName, item, 1) //获取子级数据，子节点
          if (child.length > 0) {
            node.children = child
          }
          options.push(node)
        })
      }
      this.option = options
    },
    //获取子级选项，name为当前显示字段，data为该字段的当前值，index为第几级
    getChildren(name, data, index) {
      let option = []
      if (index >= this.fields.length) { //已达到最后一级
        return option //向上一级返回子节点
      } else {
        this.fields[index].datas.map((item) => {
          if (item.parent === name) { //父级字段等于上当前的显示字段
            [...new Set(this.tableData.filter((field) => {
              return field[name] === data  //从所有数据中过滤字段为当前字段，且值为当前值的行
            }).map((field)=>{
              return field[item.fieldName] //返回各行的对应该级显示字段的值，并通过...new Set()去重
            }))].map((field) => {
              let node = { //构造节点
                label: field,
                value: field
              }
              let child = this.getChildren(item.fieldName, field, index+1) //获取下一级数据，下一级子节点
              if (child.length > 0) {
                node.children = child
              }
              option.push(node)
            })
          }
        })
        return option
      }
    }
  }
}

</script>
